// src/composables/useValidation.js
import { reactive, computed } from 'vue'

/**
 * 表单验证组合式函数
 * @param {Object} rules - 验证规则 { fieldName: validatorFn }
 * @param {Object} initialValues - 初始值
 * @returns {Object} { formData, errors, validate, reset }
 */
export function useValidation(rules, initialValues = {}) {
  const formData = reactive({ ...initialValues })
  const errors = reactive({})

  // 验证单个字段
  const validateField = (name, value) => {
    const rule = rules[name]
    if (rule) {
      const error = rule(value, formData)
      errors[name] = error || ''
    }
  }

  // 全局验证
  const validate = () => {
    let isValid = true
    for (const name in rules) {
      const value = formData[name]
      const error = rules[name](value, formData)
      errors[name] = error || ''
      if (error) isValid = false
    }
    return isValid
  }

  // 重置表单
  const reset = () => {
    Object.assign(formData, initialValues)
    for (const key in errors) {
      errors[key] = ''
    }
  }

  // 是否有错误（用于禁用提交按钮）
  const hasErrors = computed(() => {
    return Object.values(errors).some((err) => err)
  })

  return {
    formData,
    errors,
    validate,
    reset,
    validateField,
    hasErrors,
  }
}
